/*     Copyright (c) 2018, jymenu.com. All rights reserved.   */
package com.yunhaikeji.api.common;

import com.yunhaikeji.core.jwt.JwtUser;
import com.yunhaikeji.core.util.DateUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.io.File;
import java.util.Date;

/**
 * BaseController
 *
 * @author : zhuo
 * @date : 2018/8/3 23:22
 * @description :
 */
public abstract class BaseController {
    /**
     * 初始化数据绑定
     * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击
     * 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        //Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });

       /* //为createBy、updateBy赋值
        binder.registerCustomEditor(String.class, "createBy", new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(getSysUser().getId());
            }
        });

        binder.registerCustomEditor(String.class, "updateBy", new PropertyEditorSupport() {
            @Override
            public void setAsText(String text){
                setValue(getSysUser().getId());
            }
        });*/
    }

    public JwtUser getSysUser() {
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        return (JwtUser) token.getPrincipal();
    }

    //根据文件系统路径 删除文件
    public boolean delFileByUrl(String path) {
        File f = new File(path);
        //f.deleteOnExit();  英文不好坑死爹啊
        return f.delete();
    }
}
